<template>
  <view class="page-wrapper ticket-booking-page page">
    <div class="page-title">订票 Book Tickets</div>
    <div class="wrap">
      <div class="title">时间 Time</div>
      <div class="te" style="display: flex">
        <div
          class="date-button"
          :class="{ active: monCurrent == index }"
          v-for="(item, index) in monthArr"
          @click="selectMonth(index)"
          :key="index"
        >
          {{ formatMonthYear(item.displayMonth) }}
        </div>
      </div>
      <div class="calendar" v-if="monCurrent >= 0">
        <calendar
          :config="monthArr[monCurrent]"
          :selectedDate="selectedDate"
          @update:selectedDate="handleSelectedDate"
        />
      </div>

      <div class="time-rangel-box" v-if="monCurrent >= 0">
        <div
          class="item"
          :class="{ active: curTime.id == item.id }"
          @click="selectTime(item)"
          v-for="item in timeArr"
          :key="item.id"
        >
          {{ item.time[0] + '-' + item.time[1] }}
        </div>
      </div>
      <div class="title">类别 Type</div>
      <div class="te">
        <div
          class="button type-button"
          :class="{ active: curType.id == item.id }"
          @click="selectType(item)"
          v-for="item in info.priceList"
          :key="item.id"
        >
          {{ item.name }} {{ item.enName }} ¥ {{ item.price }}
        </div>
      </div>
      <div class="tips" v-if="curType.name !== '成人票'">
        *购买特殊票需携带相关证件现场核验。 <br />
        *On-site verification with relevant documents required.
      </div>
      <div class="title">数量 Quantity</div>
      <div class="te">
        <uv-number-box v-model="count" @change="valChange"></uv-number-box>
      </div>
    </div>
    <div class="bottom-control-box">
      <div class="bottom-control-container">
        <div class="wrap">
          <div class="total-price disabled" v-if="!curType.id">¥ --</div>
          <div class="total-price" v-else>
            <text>¥{{ curType.price }}</text>
          </div>
          <div class="book-button" :class="{ disabled: !curType.id }" @click="toConfirm">确认 Confirm</div>
        </div>
        <div :style="{ height: bottomSafeArea + 'px' }"></div>
      </div>
      <div class="place" :style="{ height: `calc(${bottomSafeArea}px + 100rpx)` }"></div>
    </div>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, watch, computed } from 'vue'
import { useStore } from 'vuex'
import { exhibitionInfo } from '@/utils/api/exhibition'
import { onLoad } from '@dcloudio/uni-app'
import { roundNumber } from '@/utils/reg'

// 使用 Vuex 获取系统安全区高度（底部）
const store = useStore()
const bottomSafeArea = computed(() => store.getters['system/bottomSafeArea'])

const isVip = computed(() => store.getters['user/isVip'])
// 接收页面参数 id（从 URL 或上一页传入）
let id: string = ''

// 当前选中的票数
let count = ref<number>(1)
// 当前选中的类型
let curType = ref<any>({})
// 当前选中的时间段
let curTime = ref<any>({})

const valChange = (val: number) => {
  console.log('数量变化', val)
}

// 默认日历配置（可删除或根据接口数据动态填充）
let dateConfig = ref({
  displayMonth: '2025-06',
  specialDays: [
    {
      start: 1,
      end: 10
    },
    {
      start: 15,
      end: 20
    }
  ]
})

// 当前选中月份索引
let monCurrent = ref<number>(-1)

// 当前选中日期
const selectedDate = ref('')
const handleSelectedDate = (date: any) => {
  console.log('接收选中的日期', date)
  selectedDate.value = date
}

// 展览信息数据存储
const info = ref<any>({})

const lastPrice = computed(() => {
  console.log('计算价格', curType.value.price)
  let price = isVip.value ? curType.value.price * count.value * 0.9 : curType.value.price * count.value

  return roundNumber(price, 2)
})
// 切换月份
const selectMonth = (index: number) => {
  monCurrent.value = index
  selectedDate.value = ''
}

// 安全解析 JSON 字符串，避免异常中断
function safeParse(jsonString: string): any {
  try {
    return jsonString ? JSON.parse(jsonString) : null
  } catch (e) {
    console.error('JSON 解析失败:', e)
    return null
  }
}

// 格式化月份显示为 "MM.YYYY"
const formatMonthYear = (dateStr: string): string => {
  if (!dateStr || !dateStr.includes('-')) return ''
  const [year, month] = dateStr.split('-')
  return `${month}.${year}`
}

// 将时间段拆解为每天
function splitRangeToDays(start: Date, end: Date): Date[] {
  const days: Date[] = []
  let currentDate = new Date(start)
  while (currentDate <= end) {
    days.push(new Date(currentDate))
    currentDate.setDate(currentDate.getDate() + 1)
  }
  return days
}

// 合并连续日期为区间
function mergeDaysToRanges(days: number[]): { start: number; end: number }[] {
  if (days.length === 0) return []
  days.sort((a, b) => a - b)
  const ranges = []
  let startDay = days[0]
  for (let i = 1; i < days.length; i++) {
    if (days[i] !== days[i - 1] + 1) {
      ranges.push({ start: startDay, end: days[i - 1] })
      startDay = days[i]
    }
  }
  ranges.push({ start: startDay, end: days[days.length - 1] })
  return ranges
}

// 处理时间数据（按月归类 + 区间合并）
let monthArr = ref<any[]>([])
let timeArr = ref<any[]>([])

const processTime = (timeJson) => {
  const result = {}

  timeJson.forEach((item) => {
    let [startDateStr, endDateStr] = item.time
    const start = new Date(startDateStr)
    const end = new Date(endDateStr)

    if (isNaN(start.getTime()) || isNaN(end.getTime())) return

    const days = splitRangeToDays(start, end)

    days.forEach((day) => {
      const year = day.getFullYear()
      const month = String(day.getMonth() + 1).padStart(2, '0')
      const dayOfMonth = day.getDate()
      const key = `${year}-${month}`

      if (!result[key]) {
        result[key] = []
      }

      result[key].push(dayOfMonth)
    })
  })

  const finalResult = []

  Object.keys(result).forEach((displayMonth) => {
    const uniqueDays = [...new Set(result[displayMonth])]
    const ranges = mergeDaysToRanges(uniqueDays)

    finalResult.push({
      displayMonth,
      specialDays: ranges
    })
  })

  finalResult.sort((a, b) => {
    const [y1, m1] = a.displayMonth.split('-').map(Number)
    const [y2, m2] = b.displayMonth.split('-').map(Number)
    return y1 !== y2 ? y1 - y2 : m1 - m2
  })

  return finalResult
}

// 提取时间段列表
const getTimeStep = (periodJson) => {
  return periodJson.map((item) => ({
    ...item,
    time: item.time.map((timeStr) => {
      const match = timeStr.match(/\d{2}:\d{2}/)
      return match ? match[0] : timeStr
    })
  }))
}

// 获取展览信息
const getInfo = async () => {
  const { code, data } = await exhibitionInfo({ id })
  if (code == 200) {
    info.value = data
    const timeJson = safeParse(data.timeJson)
    const periodJson = safeParse(data.periodJson)
    if (timeJson) monthArr.value = processTime(timeJson)
    if (periodJson) timeArr.value = getTimeStep(periodJson)
  }
}

const selectType = (item: any) => {
  curType.value = item
}

const selectTime = (item: any) => {
  console.log('item', item)
  curTime.value = item
}

const toConfirm = () => {
  if (!selectedDate.value || selectedDate.value === '') {
    return uni.showToast({
      title: '请选择日期',
      icon: 'none'
    })
  }
  if (!curTime.value.id || curTime.value.id === '') {
    return uni.showToast({
      title: '请选择时间段',
      icon: 'none'
    })
  }
  if (!curTime.value.id || curTime.value.id === '') {
    return uni.showToast({
      title: '请选择时间段',
      icon: 'none'
    })
  }

  let params = {
    activityPriceId: curType.value.id,
    activityPrice: curType.value,
    agreementTime: selectedDate.value,
    objectId: info.value.id,
    period: curTime.value.time,
    type: 3,
    address: info.value.address,
    enAddress: info.value.enAddress,
    name: info.value.name,
    enName: info.value.enName,
    quantity: count.value
  }
  uni.navigateTo({
    url: '/pages/ticketConfirm/ticketConfirm?params=' + JSON.stringify(params)
  })
}
// 页面加载时获取参数并请求数据
onLoad((opt) => {
  if (opt && opt.id) {
    id = opt.id
    getInfo()
  }
})
</script>

<style lang="scss" scoped>
@import '../ticketBooking/ticketBooking.scss';
</style>
